package com.ouc.eddyAlgorithm.dao.impl;

import com.ouc.common.entity.NcData;
import com.ouc.common.utils.nc.NcUtil;
import com.ouc.eddyAlgorithm.dao.PetNcDao;
import org.springframework.stereotype.Component;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author B504
 * @date 2023/2/1
 * @apiNote
 */
@Component
public class PetNcDaoImpl implements PetNcDao {
  @Override
  public NcData getPetNcData(Variable variable, Integer startIndex, Integer endIndex) throws IOException, InvalidRangeException {
    NcData ncData = NcUtil.getDataOfSlice(variable);
    if (ncData.getData1D() != null) {
      startIndex = startIndex == null ? 0 : startIndex;
      endIndex = endIndex == null ? ncData.getData1D().length : endIndex;
      endIndex = endIndex > ncData.getData1D().length ? ncData.getData1D().length : endIndex;
      float[] arrFloat = new float[endIndex - startIndex];
      System.arraycopy(ncData.getData1D(), startIndex, arrFloat, 0, endIndex - startIndex);
      ncData.setData1D(arrFloat);
    } else if (ncData.getData2D() != null) {
      startIndex = startIndex == null ? 0 : startIndex;
      endIndex = endIndex == null ? ncData.getData2D().length : endIndex;
      endIndex = endIndex > ncData.getData2D().length ? ncData.getData2D().length : endIndex;
            float[][] arrFloat = new float[endIndex - startIndex][ncData.getData2D()[0].length];
      System.arraycopy(ncData.getData2D(), startIndex, arrFloat, 0, endIndex - startIndex);
      ncData.setData2D(arrFloat);
    }

    return ncData;
  }

  @Override
  public Map<String, NcData> getPetNcDataToMap(NetcdfFile ncFile, Integer startIndex, Integer endIndex) {
    Map<String, NcData> map = new HashMap<>();
    try {
      List<Variable> variables = ncFile.getVariables();
      for (Variable variable : variables) {
        map.put(variable.getShortName(), getPetNcData(variable, startIndex, endIndex));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return map;
  }
}
